package com.cn.march.controller.weChat;

import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cn.march.base.protocol.WeChatTextMsg;
import com.cn.march.base.weChatUtil.CheckUtil;
import com.cn.march.model.weChat.WeChatParameter;

@Controller
@RequestMapping("/weChat")
public class WeChatController {

	@RequestMapping(value = "/checkConnet", method = RequestMethod.GET)
	@ResponseBody
	public void connetWeChat(WeChatParameter record, HttpServletResponse resp) throws Exception {
		String echostr = record.getEchostr();// 随机字符串
		String nonce = record.getNonce();// 随机数
		String signature = record.getSignature();// 微信加密签名
		String timestamp = record.getTimestamp();// 时间戳

		PrintWriter out = resp.getWriter();

		boolean code = CheckUtil.checkSignature(signature, timestamp, nonce);

		if (code) {
			out.print(echostr);
		}
	}

	@RequestMapping(value = "/checkConnet", method = RequestMethod.POST)
	@ResponseBody
	public void connetWeChat(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		String backMsg = null;
		PrintWriter out = resp.getWriter();
		Map<String, String> map = CheckUtil.xmltoMapMessage(req);
		String toUserName = map.get("ToUserName");
		String fromUserName = map.get("FromUserName");
		String msgType = map.get("MsgType");
		String content = map.get("Content");

		if (CheckUtil.MESSAGE_TEXT.equals(msgType)) {

			switch (content) {
			case "?":
				backMsg = CheckUtil.initText(fromUserName, toUserName, content);
				break;
			case "？":
				backMsg = CheckUtil.initText(fromUserName, toUserName, content);
				break;
			case "1":
				backMsg = CheckUtil.backOne(fromUserName, toUserName, content);
				break;
			case "2":
				backMsg = CheckUtil.backTwo(fromUserName, toUserName, content);
				break;
			case "3":
				backMsg = CheckUtil.backThree(fromUserName, toUserName, content);
				break;
			default:
				backMsg = CheckUtil.initText(fromUserName, toUserName, content);
				break;
			}
		}

		if (CheckUtil.MESSAGE_EVENT.equals(msgType)) {
			String eventType = map.get("Event");
			switch (eventType) {
			case CheckUtil.MESSAGE_SUBSCRIBE:
				backMsg = CheckUtil.initText(fromUserName, toUserName, content);
				break;
			default:
				break;
			}
		}

		out.print(backMsg);
		out.close();

	}

}
